import { useEffect, useRef, useState } from "react";
import Taro from "@tarojs/taro";

export default function usePage(props) {
  const pageNo = useRef(1);
  const [loadMore, setLoadMore] = useState(0); // 0 | 1 | 2
  const [empty, setEmpty] = useState(false);
  const [listData, setListData] = useState([]);
  const [refreshing, setRefreshing] = useState(false);

  useEffect(() => {
    onPull().then();
  }, [props.params]);

  async function onPull() {
    if (refreshing) return;
    setTimeout(() => setRefreshing(true));
    pageNo.current = 1;
    setListData([]);

    const params = {
      ...props?.params,
      pageNum: 1,
    };

    try {
      const result = await props.request(params);

      if (!result?.success) {
        await Taro.showToast({
          icon: "error",
          title: result?.msg || "请求错误",
        });
      }

      const list = [...(result?.data?.list || [])];

      setListData(list);
      setEmpty(list?.length === 0);
      setLoadMore(list?.length === result?.data?.total || 0 ? 2 : 0);
    } finally {
      setTimeout(() => setRefreshing(false), 500);
    }
  }

  async function onLoad() {
    if (loadMore !== 0 || refreshing) return;

    const pageNum = pageNo.current + 1;

    setLoadMore(1);

    const params = {
      ...props?.params,
      pageNum,
    };

    const result = await props.request(params);

    if (!result?.success) {
      await Taro.showToast({
        icon: "error",
        title: result?.msg || "请求错误",
      });
    }

    const list = [...listData, ...(result?.data?.list || [])];

    setListData(list);

    if (list?.length === result?.data?.total) {
      setLoadMore(2);
      return;
    }

    setLoadMore(0);
    pageNo.current = pageNum;
  }

  return {
    loadMore,
    refreshing,
    empty,
    listData,
    onPull,
    onLoad,
  };
}
